package com.example.tetris.restore;

import com.example.tetris.App;
import com.example.tetris.gui.GamePageController;
import com.example.tetris.logics.controller.GameManager;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;

import java.io.*;

public class GameSave {
    public static void saveGame(GameManager gameManager){
        String file = "gameSave.bat";
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) {
            out.writeObject(gameManager);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void loadGame(){
        GamePageController gamePageController = null;
        GameManager gameManager = null;
        Parent root = null;

        FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource("gamePage.fxml"));
        try {
            root = fxmlLoader.load();//此时相当于是一个新游戏的画面
            gamePageController = fxmlLoader.getController();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            String file = "gameSave.bat";
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            gameManager = (GameManager) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        gameManager.setGamePageController(gamePageController);
        gamePageController.setGameManager(gameManager);
        gamePageController.paintBoard();

        App.setRoot(root);



    }

}
